from django.contrib import admin
from .models import *
from .forms import *
from django.shortcuts import render_to_response
from django.contrib import messages
# Register your models here.


class RepoAdmin(admin.ModelAdmin):
    form = RepoForm
    list_display = ('id', 'name', 'no', 'price_per_100g_1d',)

    def get_readonly_fields(self, request, obj=None):
        if obj is None:
            return []
        else:
            return ['no', ]

    def save_model(self, request, obj, form, change):
        if change:
            cdata = form.cleaned_data
            obj.save()
        else:
            if self.model.objects.filter().count() > 0:
                return messages.error(request, '当前只允许存在一个仓库')
            obj.save()

    def has_delete_permission(self, request, obj=None):
        return False

    def has_add_permission(self, request):
        return True

    def has_change_permission(self, request, obj=None):
        return True

admin.site.register(Repo, RepoAdmin)


class StoreUnitAdmin(admin.ModelAdmin):
    list_display = ['id', 'no', 'repo', 'fields', 'in_use', 'repo_no']
    search_fields = ['id', 'repo_no']
    list_filter = ('in_use', 'repo')
    fields = ['repo', 'parent_type', 'repo_no', 'in_use']

    def get_readonly_fields(self, request, obj=None):
        return [f.name for f in  self.model._meta.fields]

    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj=None):
        return False
admin.site.register(StoreUnit, StoreUnitAdmin)
